package com.example.game.controller;

import com.example.game.entity.User;
import com.example.game.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class GameController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "login"; // 返回视图名称
    }

    @GetMapping("/")
    public String index() {
        return "index"; // 返回视图名称，不包含扩展名
    }


    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {
        User user = userService.getUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            model.addAttribute("error", "用户名或密码错误");
            return "login"; // 返回登录视图
        }
        session.setAttribute("user", user);
        return "redirect:/game"; // 重定向到游戏页面
    }

    @GetMapping("/register")
    public String registerPage() {
        return "register"; // 应返回视图名称"register"
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           Model model) {
        boolean success = userService.registerUser(username, password);
        if (!success) {
            model.addAttribute("error", "用户名已存在");
            return "register"; // 返回注册视图
        }
        return "redirect:/login"; // 注册成功后重定向到登录页
    }

    @GetMapping("/game")
    public String gamePage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login"; // 未登录则重定向到登录页
        }
        return "game"; // 返回游戏视图
    }

    @PostMapping("/submitScore")
    public String submitScore(@RequestParam int score,
                              HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            userService.updateUserScore(user.getUsername(), score);
        }
        return "redirect:/scoreboard"; // 提交分数后重定向到排行榜
    }

    @GetMapping("/scoreboard")
    public String scoreboard(Model model) {
        model.addAttribute("topUsers", userService.getTopUsers(10));
        return "scoreboard"; // 返回排行榜视图
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/"; // 登出后重定向到首页
    }
}